package com.chenwc.serialassistant.threadpool.supplier;

import com.chenwc.serialassistant.util.Common;
import com.chenwc.serialassistant.util.LoadConfigInfo;
import gnu.io.SerialPort;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 获取串口数据
 *
 * @author chenwc
 */
public class GetSerialPortDataSupplier implements Supplier<String> {

    private final static Logger logger = LoggerFactory.getLogger(GetSerialPortDataSupplier.class);

    /**
     * 读取配置文件
     */
    private final LoadConfigInfo loadConfigInfo = new LoadConfigInfo();

    private final SerialPort serialPort;

    public GetSerialPortDataSupplier(SerialPort serialPort) {
        this.serialPort = serialPort;
    }

    @Override
    public String get() {
        String recv = "";
        InputStream inputStream = null;
        try {
            //获得串口的输入流
            inputStream = serialPort.getInputStream();
            int size = 0;
            //读取5次还是0则退出循环，避免死循环，用于检测分包传输
            int wait = 5;
            while ((size == 0) && (wait-- > 0)) {
                size = inputStream.available();
            }
            logger.info("inputStream.available: {}", size);
            if (size > 0) {
                byte[] tp = new byte[1];
                List<Byte> list = new ArrayList<>();
                while (inputStream.read(tp) > 0) {
                    list.add(tp[0]);
                }
                recv = new String(Common.listByteToByte(list), loadConfigInfo.getSerialPortReadDataCharsetName());
                logger.info("接收的数据长度：{}", list.size());
            } else {
                logger.info("inputStream.available <= 0");
            }
        } catch (IOException e) {
            logger.error("读取串口数据时 IO 异常！");
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return recv;
    }


}